package week9;

/**
 * Created by Administrator on 2016/4/30.
 */
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Map;

public class BeanUtil {
    public static <T> T getBean(Map<String, Object> data, String clzName) throws Exception {
        Class clz = Class.forName(clzName);
        Object bean = clz.newInstance();
        data.entrySet().forEach(entry -> {
            String setter = String.format("set%s%s",
                    entry.getKey().substring(0, 1).toUpperCase(),
                    entry.getKey().substring(1));
            try {
                Method method = clz.getMethod(setter, entry.getValue().getClass());
                if (Modifier.isPublic(method.getModifiers())) {
                    method.invoke(bean, entry.getValue());
                }
            } catch (IllegalAccessException | IllegalArgumentException | NoSuchMethodException | SecurityException | InvocationTargetException ex) {
                throw new RuntimeException(ex);
            }
        });
        return (T) bean;
    }
}